﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using SqlBuilder;

namespace Main.Domain
{
    internal class TablesUCViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<TableStructure> tables;

        public ObservableCollection<TableStructure> Tables
        {
            get=> tables;
            set
            {
                tables = value;
                OnPropertyChanged();
            }
        }
        private ObservableCollection<TableStructure> _allTables;

        public TablesUCViewModel()
        {
            Init();
            FilterTables(null);
        }
        public async void Init()
        {
            var tables = Functions.GetSingleton<List<TableStructure>>();
            if (tables == null)
            {
                tables = await Functions.GetTableStructure();
                tables.SetSingleton();
            }
            _allTables = new ObservableCollection<TableStructure>(tables);
        }

        private string _searchKeyword;

        public string SearchKeyword
        {
            get => _searchKeyword;
            set
            {
                _searchKeyword = value;
                OnPropertyChanged();
                FilterTables(_searchKeyword);
            }
        }
        private void FilterTables(string keyword)
        {
            var filteredTables =
                string.IsNullOrWhiteSpace(keyword) ?
                _allTables :
                _allTables.Where(i => i.Name.Contains(keyword!.ToUpper()) || (i.Comments != null && i.Comments.Contains(keyword!.ToUpper())));

            Tables = new ObservableCollection<TableStructure>(filteredTables);
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
